package controllers

import (
	"github.com/revel/revel"
	"golang.org/x/crypto/bcrypt"
	"wuhuaguo.com/whg01/app/models"
	"wuhuaguo.com/whg01/app/routes"
)

type Application struct {
	GorpController
}

// 检查用户信息
func (c Application) CheckUser() revel.Result {
	if c.Request.RequestURI == "/login/index.html" ||
		c.Request.RequestURI == "/Application/Login" ||
		c.Request.RequestURI == "/register" {
		return nil
	}
	if user := c.connected(); user == nil {
		c.Flash.Error("Please log in first")
		revel.INFO.Println("check User  user: nil")
		return c.Redirect("/login/index.html")
	} else {
		c.RenderArgs["user"] = user
	}
	return nil
}

func (c Application) AddUser() revel.Result {
	if user := c.connected(); user != nil {
		c.RenderArgs["user"] = user
		revel.INFO.Println("add user " + user.Name)
	}
	return nil
}

// pc端陆没有游客概念
func (c Application) connected() *models.User {
	if c.RenderArgs["user"] != nil {
		return c.RenderArgs["user"].(*models.User)
	}
	if userid, ok := c.Session["userid"]; ok {
		return c.getUserByUserid(userid)
	}
	//返回游客账号
	//判断浏览器
	return nil
}

//获取用户信息
func (c Application) getUserByUserid(userid string) *models.User {
	revel.INFO.Printf("user access userid: %s", userid)
	return models.GetUserByUserId(userid)
}

func (c Application) Index() revel.Result {
	user := c.connected()

	if user == nil {
		//进入登陆状态
		return c.Redirect("/login/index.html")
	}

	revel.INFO.Println("user: %q login", user.Username)
	c.Session["userid"] = user.UseridStr()

	//判断用户权限：
	// if user.Role == models.ROOT {
	// 	merchats := models.GetALLMerchant()
	// 	return
	// }

	//root 权限

	//商户管理员
	return c.Render(user)
}

func (c Application) Register() revel.Result {
	return c.Render()
}

func (c Application) SaveUser(user models.User, verifyPassword string) revel.Result {
	c.Validation.Required(verifyPassword)
	c.Validation.Required(verifyPassword == user.Password).
		Message("Password does not match")
	user.Validate(c.Validation)

	if c.Validation.HasErrors() {
		c.Validation.Keep()
		c.FlashParams()
		return c.Redirect(routes.Application.Register())
	}
	//判断用户名是否已经注册
	if models.GetUserByUsername(user.Username) != nil {
		return c.RenderText("用户名 " + user.Username + " 已经被注册， 请刷新重新注册")
	}

	newuser := models.CreateUserByUsernameAndPassword(user)

	c.Session["userid"] = newuser.UseridStr()
	c.Flash.Success("Welcome, " + newuser.Name)
	return c.Redirect(routes.Application.Index())
}

func (c *Application) LoginIndex() revel.Result {
	return c.Render()
}

func (c Application) Login(username, password string, remember bool) revel.Result {
	user := models.GetUserByUsername(username)
	if user != nil {
		err := bcrypt.CompareHashAndPassword(user.HashedPassword, []byte(password))
		if err == nil {
			c.Session["userid"] = user.UseridStr()
			if remember {
				c.Session.SetDefaultExpiration()
			} else {
				c.Session.SetNoExpiration()
			}
			c.Flash.Success("Welcome, " + username)
			return c.Redirect(routes.Application.Index())
		}
	}

	c.Flash.Out["username"] = username
	c.Flash.Error("登录失败，账号或密码错误！")
	return c.Redirect(routes.Application.LoginIndex())
}

func (c Application) Logout() revel.Result {
	for k := range c.Session {
		delete(c.Session, k)
	}
	return c.Redirect(routes.Application.Index())
}

//在首页列表展示区域的商品
func (c Application) boxListItems() ([]*models.ItemToRender, error) {
	results, err := c.Txn.Select(models.Item{}, `select * from item where DisplayPos = ?`, 1)
	if err != err {
		return nil, err
	}
	var irs []*models.ItemToRender
	for _, r := range results {
		i := r.(*models.Item).ItemToRender()
		irs = append(irs, i)
	}
	return irs, nil
}

func (c Application) SellerRegister() revel.Result {
	return c.Render()
}

/*
* 管理端  商户管理自己的商品数据
 */

func (c Application) SellerAdmin() revel.Result {
	return c.Render()
}
